﻿using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace Granite.Wcf.PocoService
{
	/// <summary>
	/// This service host auto-generates the contract for the associated type.
	/// </summary>
	/// <remarks>Based on http://blogs.msdn.com/b/carlosfigueira/archive/2011/03/22/wcf-extensibility-iservicebehavior.aspx </remarks>
	public class PocoServiceHost : ServiceHost
	{
		readonly IInstanceProvider m_InstanceProvider;

		public PocoServiceHost(object singleton, Uri baseAddress)
			: base(singleton.GetType(), baseAddress)
		{
			m_InstanceProvider = new SingletonInstanceProvider(singleton);
		}

		public PocoServiceHost(Type serviceType, Uri baseAddress)
			: base(serviceType, baseAddress)
		{
			m_InstanceProvider = new DefaultInstanceProvider(serviceType);
		}

		public PocoServiceHost(Type serviceType, Uri baseAddress, Func<object> instanceProvider)
			: base(serviceType, baseAddress)
		{
			m_InstanceProvider = new DelegateInstanceProvider(instanceProvider);
		}


		/// <summary>
		/// Initializes the runtime for the service host.
		/// </summary>
		/// <exception cref="T:System.InvalidOperationException">
		/// The description of the service hosted is null.
		/// </exception>
		protected override void InitializeRuntime()
		{
			Description.Behaviors.Add(new Granite.Wcf.PocoService.PocoServiceBehavior() { InstanceProvider = m_InstanceProvider });
			Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
			base.InitializeRuntime();
		}

	}
}

